package com.shj.controller;

import com.alibaba.fastjson.JSONObject;
import com.shj.entity.MenuTreeNode;
import com.shj.entity.SysMenu;
import com.shj.service.MenuTreeService;
import com.shj.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author songhuajian
 * @Date 2020/5/2 17:24
 **/
@Controller("SysMenuController")
@RequestMapping("/system/menu")
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private MenuTreeService menuTreeService;

    @RequestMapping("/find")
    public String find(Model model) {
        List<SysMenu> list = sysMenuService.findAll();
        model.addAttribute("list", list);
        return "menu/menu_list";
    }

    @RequestMapping("/openAdd")
    public String openAdd(Model model){
        // 构建父节点为0的权限树
        List<MenuTreeNode> list = menuTreeService.tree("0", null);
        //
        list = menuTreeService.getChildNodeList(list);
        model.addAttribute("list", list);
        return "menu/menu_add";
    }

    @RequestMapping("/add")
    public String add(Model model, SysMenu sysMenu) {
        String menuPid = sysMenu.getMenuPid().split("-")[0];
        String pLevel = sysMenu.getMenuPid().split("-")[1];

        int level = Integer.parseInt(pLevel);
        level += 1;
        sysMenu.setMenuPid(menuPid);
        sysMenu.setLevel(level);
        sysMenuService.add(sysMenu);
        return find(model);
    }

    @RequestMapping("/openUpdate")
    public String openUpdate(Model model, String menuId) {
        SysMenu sysMenu = sysMenuService.findByMenuId(menuId);
        model.addAttribute("menu", sysMenu);
        return "menu/menu_edit";
    }

    @RequestMapping("/edit")
    public String update(Model model, SysMenu sysMenu) {
        sysMenuService.update(sysMenu);
        return find(model);
    }

    @RequestMapping("/delete")
    public String delete(Model model, String menuId) {
        sysMenuService.delete(menuId);
        return find(model);
    }

    /**
     * @Description 构造权限树
     * @author songhuajian
     * @date 2020/5/9 23:39
     */
    @RequestMapping("/tree")
    @ResponseBody
    public List<MenuTreeNode> tree(String treeId, String roleId) {
        return menuTreeService.tree(treeId, roleId);
    }
}
